var express = require('express');
var router = express.Router();
let {db} = require('../mysql/db')


// 定义一个中间件  进行session登录认证

let islogin = false  //默认未登录
let mw1 = (req,res,next)=>{
  // 判断是否处于登录状态
  if(req.session.islogin){//登录
    islogin = req.session.islogin
  }else{
    islogin = false  //如果不写有bug
  }
  next()
}


// 首页路由
router.get('/',mw1,(req,res)=>{
  console.log(islogin)  //登录状态



  let catas = []  //存储图书分类
  let books = []  //存储图书

  // 获取图书分类
  let sql = 'select * from cataory;select * from book;';
  db.query(sql,(err,data)=>{
    if(err){
      return console.log('数据获取失败',err)
    }
    // 处理图书分类语句
    for(let cat of data[0]){
      catas.push(cat.cataory)
    }
    console.log(catas)  //图书分类列表


    console.log(data[1])
    for(let book of data[1]){
      books.push({
        id:book.id,
        bookname:book.bookname,
        author:book.author,
        tag:book.tag,
        bookimg:book.bookimg,
        cataory:book.cataory,
      })
    }

    console.log(books)
    





    res.render('index.ejs',{
      title:'Sobook',
      islogin:islogin,
      uname:req.session.uname,
      catas:catas,
      books:books,
    })
  })
  
  


})






module.exports = router;
